package com.kiku.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kiku.reggie.dto.DishDto;
import com.kiku.reggie.entity.Dish;
import com.kiku.reggie.entity.DishFlavor;
import com.kiku.reggie.mapper.DishMapper;
import com.kiku.reggie.service.DishFlavorService;
import com.kiku.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @className: DishServiceImpl
 * @description: TODO 类描述
 * @author: kiku
 * @date: 2023/10/19 21:49
 **/
@Service
//由于涉及多张表的操作，因此需要加入事务控制
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService{
    @Autowired
    private DishFlavorService dishFlavorService;
    //实现新增菜品并且插入菜品对应的口味数据
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish表
        this.save(dishDto);
        //这是菜品的id
        Long dishId = dishDto.getId();
        //保存菜品的口味数据到dish_flavor
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(flavors);

    }
    //根据id查询菜品信息和口味信息
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品的基本信息(dish表)
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        //查询菜品的口味信息(dish_flavor表)
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //进行菜品表的更新
        this.updateById(dishDto);
        //对菜品口味表的对应口味数据进行删除
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //添加当前提交过来的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);

    }
}
